package com.roseski.controller;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.roseski.dto.OrderListReq;
import com.roseski.dto.OrderListResp;
import com.roseski.dto.OrderReq;
import com.roseski.dto.PageDto;
import com.roseski.dto.ServiceResult;
import com.roseski.dto.UserCacheDto;
import com.roseski.enums.OrderStatusEnum;
import com.roseski.model.RoseskiMember;
import com.roseski.model.RoseskiOrder;
import com.roseski.model.RoseskiPayOrder;
import com.roseski.service.RoseskiMemberService;
import com.roseski.service.RoseskiOrderService;
import com.roseski.service.impl.RedisServiceImpl;
import com.roseski.service.impl.WechatPayServiceImpl;
import com.roseski.util.ErrorCodeEnum;
/**
 * 订单接口
 * @author chen
 *
 */
@RestController
@RequestMapping(value = "order/order")
public class OrderController {
	
    Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());
	
    @Resource
	RedisServiceImpl redisServiceImpl;
	@Autowired
	RoseskiMemberService roseskiMemberService;
	@Autowired
	RoseskiOrderService roseskiOrderService;
	@Autowired
	WechatPayServiceImpl wechatPayServiceImpl;
	
	@RequestMapping(value="creatOrder")
	public ServiceResult<Map<String,String>> creatOrder(@RequestBody OrderReq orderReq){
		logger.info("creatOrder(),请求参数:{}", orderReq);
		ServiceResult<Map<String,String>> ret = new ServiceResult<Map<String,String>>();
		ret.setCode(ErrorCodeEnum.SUCCESS.getCode());
		ret.setMessage(ErrorCodeEnum.SUCCESS.getMsg());
		try {
			String val = redisServiceImpl.get(orderReq.getToken());
			if(!StringUtils.isEmpty(val)) {
				UserCacheDto dto = JSON.parseObject(val, UserCacheDto.class);
				RoseskiMember member = roseskiMemberService.queryByOpenId(dto.getOpenid());
				if(member == null) {
					ret.setCode(ErrorCodeEnum.MEMBER_NOT_EXISTIS.getCode());
					ret.setMessage(ErrorCodeEnum.MEMBER_NOT_EXISTIS.getMsg());
					return ret;
				}
				//创建订单
				RoseskiPayOrder payOrder = roseskiOrderService.createOrder(orderReq, member);
				Map<String,String> map = wechatPayServiceImpl.createOrder(payOrder, member.getOpenId());
				ret.setData(map);
				return ret;
			}else {
				ret.setCode(ErrorCodeEnum.TOKEN_EXPIRE.getCode());
				ret.setMessage(ErrorCodeEnum.TOKEN_EXPIRE.getMsg());
			}
		}catch(Exception e) {
			logger.error("creatOrder(),请求信息：" + orderReq, e);
			ret.setCode(ErrorCodeEnum.UNKNOWN.getCode());
			ret.setMessage(ErrorCodeEnum.UNKNOWN.getMsg());
		}
		return ret;
	}
	
	@RequestMapping(value="userPayState")
	public ServiceResult<String> userPayState(OrderReq orderReq){
		logger.info("userPayState(),请求参数:{}", orderReq);
		ServiceResult<String> ret = new ServiceResult<String>();
		ret.setCode(ErrorCodeEnum.SUCCESS.getCode());
		ret.setMessage(ErrorCodeEnum.SUCCESS.getMsg());
		RoseskiOrder order = roseskiOrderService.queryOrderByOrderNo(orderReq.getOrderId());
		if(order == null) {
			ret.setCode(ErrorCodeEnum.ORDER_NOT_EXISTIS.getCode());
			ret.setMessage(ErrorCodeEnum.ORDER_NOT_EXISTIS.getMsg());
			return ret;
		}
		if(!OrderStatusEnum.SUCCESS.name().equals(order.getOrderStatus())) {
			ret.setCode(ErrorCodeEnum.ORDER_STATUS_HANDLE.getCode());
			ret.setMessage(ErrorCodeEnum.ORDER_STATUS_HANDLE.getMsg());
			return ret;
		}
		return ret;
	}
	
	@RequestMapping(value="purchaseRecords")
	public ServiceResult<PageDto<OrderListResp>> purchaseRecords(OrderListReq req){
		logger.info("purchaseRecords(),请求参数:{}", req);
		ServiceResult<PageDto<OrderListResp>> ret = new ServiceResult<>();
		ret.setCode(ErrorCodeEnum.SUCCESS.getCode());
		ret.setMessage(ErrorCodeEnum.SUCCESS.getMsg());
		try {
			String val = redisServiceImpl.get(req.getToken());
			if(!StringUtils.isEmpty(val)) {
				UserCacheDto dto = JSON.parseObject(val, UserCacheDto.class);
				RoseskiMember member = roseskiMemberService.queryByOpenId(dto.getOpenid());
				if(member == null) {
					ret.setCode(ErrorCodeEnum.MEMBER_NOT_EXISTIS.getCode());
					ret.setMessage(ErrorCodeEnum.MEMBER_NOT_EXISTIS.getMsg());
					return ret;
				}
				PageDto<OrderListResp> data = roseskiOrderService.listByMemberId(member.getMemberId(), req.getPage(), req.getPageSize());
				ret.setData(data);
			}else {
				ret.setCode(ErrorCodeEnum.TOKEN_EXPIRE.getCode());
				ret.setMessage(ErrorCodeEnum.TOKEN_EXPIRE.getMsg());
			}
		}catch(Exception e) {
			logger.error("creatOrder(),请求信息：" + req, e);
			ret.setCode(ErrorCodeEnum.UNKNOWN.getCode());
			ret.setMessage(ErrorCodeEnum.UNKNOWN.getMsg());
		}
		return ret;
	}
	
	@RequestMapping(value="updateReceiveStatus")
	public ServiceResult<String> updateReceiveStatus(OrderReq orderReq) throws Exception{
		logger.info("updateReceiveStatus(),请求参数:{}", orderReq);
		return roseskiOrderService.updateReceiveStatus(orderReq.getOrderId());
	}
	
	@RequestMapping(value="getCardMessage")
	public ServiceResult<JSONObject> getCardMessage(OrderReq orderReq){
		logger.info("getCardMessage(),请求参数:{}", orderReq);
		ServiceResult<JSONObject> ret = new ServiceResult<>();
		ret.setCode(ErrorCodeEnum.SUCCESS.getCode());
		ret.setMessage(ErrorCodeEnum.SUCCESS.getMsg());
		try {
			ret = roseskiOrderService.getCardMessage(orderReq.getOrderId());
			return ret;
		} catch (IOException e) {
			logger.error("getCardMessage(),请求信息：" + orderReq, e);
		}
		ret.setCode(ErrorCodeEnum.UNKNOWN.getCode());
		ret.setMessage("获取卡券异常");
		return ret;
	}

}
